package system;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Rezan Achmad
 */
public class Helper {

    public static String MD5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(s.getBytes());

            byte byteData[] = md.digest();

            // Convert the byte to hex format method 1
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < byteData.length; i++) {
                sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "";
    }

    public static String GenerateRandomString() {
        String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random rnd = new Random();

        StringBuilder sb = new StringBuilder(8);
        for (int i = 0; i < 8; i++) {
            sb.append(AB.charAt(rnd.nextInt(AB.length())));
        }
        return sb.toString();

    }

    public static String getBaseUrl(HttpServletRequest request) {
        if ((request.getServerPort() == 80)
                || (request.getServerPort() == 443)) {
            return request.getScheme() + "://"
                    + request.getServerName()
                    + request.getContextPath();
        } else {
            return request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath();
        }
    }

    public static String uploadFile(HttpServletRequest request, String fieldName) {

        try {
            // Folder to upload file
            String folderUpload = "upload/";
            
            // Get absolute path
            String absPath = request.getServletContext().getRealPath("/");

            // Check multipart form
            boolean isMultiPar = ServletFileUpload.isMultipartContent(request);

            if (!isMultiPar) {
                return null;
            }

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

            // Parse request
            List<FileItem> fileItems = upload.parseRequest(request);

            // Process the upload items
            for (FileItem fileItem : fileItems) {
                if (fileItem.getFieldName().equals(fieldName)) {
                    String fileName = fileItem.getName();
                    
                    File fileTo = new File(absPath + folderUpload + fileName);
                    fileItem.write(fileTo);
                    
                    return folderUpload + fileName;
                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }
}